package com.dbb.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.junit.Test;

import com.goldstone.entity.Order;

public class WordReader {

	// public

	public Table getTableFromWord(String path) throws Exception {
		FileInputStream in = new FileInputStream(path);// 载入文档
		POIFSFileSystem pfs = new POIFSFileSystem(in);
		HWPFDocument hwpf = new HWPFDocument(pfs);
		Range range = hwpf.getRange();// 得到文档的读取范围
		TableIterator it = new TableIterator(range);
		Table table = it.next();
		return table;
	}

	public Order readWord(String path) {
		Order order = new Order();
		try {
			Table tb = getTableFromWord(path);
			int trNum = 0, cellNum = 0, paraNum = 0, totalCell = 0;
			trNum = tb.numRows();
			for (int i = 0; i < tb.numRows(); i++) {
				TableRow tr = tb.getRow(i);
				cellNum = tr.numCells();
				for (int j = 0; j < tr.numCells(); j++) {
					TableCell td = tr.getCell(j);
					paraNum = tr.numParagraphs();
					totalCell ++;
					for (int k = 0; k < td.numParagraphs(); k++) {
						String text = td.getParagraph(k).text();
						text = text.replaceAll("(\r?\n(\\s*\r?\n)+)", "");
						text = text.replaceAll("", "");
						if (text.trim().length() > 0) {
							o("TotalCell:" + totalCell + ";TD:" + cellNum + ";Para:" + paraNum + ";TEXT:" + text);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return order;
	}

	public void o(Object o) {
		System.out.println(o.toString());
	}

	public void oln(Object o) {
		System.out.println(o.toString());
	}

	@Test
	public void testReadWord() {
		readWord("C:\\Dropbox\\Vivian\\Contracts\\Bl\\2012GH-YT032.doc");
	}

	public void testWord1() {
		try {
			// word 2003： 图片不会被读取
			InputStream is = new FileInputStream(new File("D:\\sinye.doc"));
			WordExtractor ex = new WordExtractor(is);
			String text2003 = ex.getText();
			System.out.println(text2003);
			// word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
			OPCPackage opcPackage = POIXMLDocument.openPackage("D:\\sinye.doc");
			POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
			String text2007 = extractor.getText();
			System.out.println(text2007);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
